package com.mdp.workflow.biz.ru.ctrl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.mdp.workflow.api.FlowTaskService;
import com.mdp.workflow.biz.ru.entity.Task;
import com.mdp.workflow.biz.ru.vo.TaskActionVo;
import com.mdp.workflow.client.service.WfSysUserService;
import com.mdp.workflow.comm.dict.TaskAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.v3.oas.annotations.Operation;
import org.flowable.bpmn.model.UserTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

import static com.mdp.core.entity.Result.ok;
import static com.mdp.core.utils.BaseUtils.map;

@RestController
@RequestMapping(value="/*/ru/task")
@Api(tags={"act_ru_task-操作接口"})
public class TaskController {
	
	static Logger logger =LoggerFactory.getLogger(TaskController.class);
	
	@Autowired
	private FlowTaskService taskService;

	@Value(value = "${mdp.platform-branch-id:platform-branch-001}")
	String platformBranchId;
	
	@Autowired
	private WfSysUserService sysUserService;


	@ApiOperation( value = "查整个流程实例的任务",notes=" ")
	@RequestMapping(value="/listByProcInstId",method=RequestMethod.GET)
	public Result listByProcInstId(@ApiIgnore @RequestParam Map<String,Object> params){
		Assert.notNull(params.get("procInstId"));
			User user=LoginUtils.getCurrentUserInfo();
			QueryWrapper<Task> qw = QueryTools.initQueryWrapper(Task.class , params).in("res.tenant_id_",user.getBranchId(),platformBranchId);
			IPage page=QueryTools.initPage();
			List<Map<String,Object>> datas = taskService.selectListMapByWhere(page,qw,params);
 			return ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());

	}

	@GetMapping("/listForRollback")
	@Operation(summary = "获取所有可回退的节点", description = "用于【流程详情】的【回退】按钮")
	public Result getTaskListByReturn(@RequestParam("id") String id) {
		Assert.notNull(id);
		List<UserTask> userTaskList = taskService.getUserTaskListByReturn(id);
		return  ok().setData(userTaskList.stream().map(k->map("name",k.getName(),"id",k.getId())).collect(Collectors.toList()));
	}

	@ApiOperation( value = "act_ru_task-查询列表",notes=" ")
	@ApiEntityParams(Task.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=Task.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listTask(@ApiIgnore @RequestParam Map<String,Object> params){
		try {

			RequestUtils.transformArray(params, "categoryIds");
			RequestUtils.transformArray(params, "tagIds");
			RequestUtils.transformArray(params, "procInstIds");
			User user=LoginUtils.getCurrentUserInfo();
			QueryWrapper<Task> qw = QueryTools.initQueryWrapper(Task.class , params).in("res.tenant_id_",user.getBranchId(),platformBranchId);
			IPage page=QueryTools.initPage(params);
			List<Map<String,Object>> datas = taskService.selectListMapByWhere(page,qw,params);
			datas=assigneeUsernameTran(datas);
			return ok("query-ok","查询成功").setData(datas).setTotal(page.getTotal());
		}catch (BizException e) {
			return Result.error(e);
		}catch (Exception e) {
			return Result.error(e);
		}
	}
	
 

	@ApiOperation( value = "act_ru_task-根据主键查询一条数据",notes=" ")
     @ApiResponses({
            @ApiResponse(code = 200,response=Task.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
    })
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(Task task) {
        Task data = (Task) taskService.getById(task.getId());
        return ok().setData(data);
    }

	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listAssigneeToAnyTasks")
	public Result listAssigneeToAnyTasks( @RequestParam Map<String,Object> params){
 		return listTask(params);
	}
	public List<Map<String,Object>> assigneeUsernameTran(List<Map<String,Object>> datas){
		if(datas==null ||datas.size()==0){
			return datas;
		}else{//assignee_,'' assignee_name
			List<String> userids=datas.stream().map(i->(String)i.get("assignee")).collect(Collectors.toList());
			Map<String,String> usersMap= sysUserService.mapByUserids(userids);
			for (Map<String, Object> data : datas) {
				data.put("assigneeName",usersMap.get(data.get("assignee")));
			}
			return datas;
		}
	}
	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listAssigneeToMeTasks")
	public Result listAssigneeToMeTasks( @RequestParam Map<String,Object> params){

		User user=LoginUtils.getCurrentUserInfo();
		if(params.containsKey("assignee") && user.getUserid().equals(params.get("assignee"))) {//如果是只查询本人相关的
			return listTask(params);
		}else if(!params.containsKey("assignee")){
			return Result.error("没有指定执行用户编号assignee，不允许查询");
		} else if(!user.getUserid().equals(params.get("assignee"))){
			return Result.error("不允许查询别人的任务");
		}

		return ok();
	}

	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listMyCandidateUserTasks")
	public Result listMyCandidateUserTasks( @RequestParam Map<String,Object> params){

		User user=LoginUtils.getCurrentUserInfo();
		params.put("candidateUser",user.getUserid());
		params.put("hxRoleids", Arrays.stream(LoginUtils.getMyRoleids()).collect(Collectors.joining(",")));
		params.put("hxDeptids",user.getDeptid());
		//todo 待优化
		return ok().setTotal(0).setData(new ArrayList<>());

	}




	@Deprecated
	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listMyCandidateGroupTasks")
	public Result listMyCandidateGroupTasks( @RequestParam Map<String,Object> params){
 		 return listMyCandidateUserTasks(params);
	}

	@Deprecated
	/**
	 * 请求,如list
	 * 分页参数 {currentPage:1,pageSize:10,total:0}
	 * 根据条件查询数据对象列表,如果不上传分页参数，将不会分页。后台自动分页，无需编程
	 * taskType 0已领取待执行的任务，1待领取的个人业务,2待领取的部门业务
	 */
	@RequestMapping(value="/listAnyCandidateGroupTasks")
	public Result listAnyCandidateGroupTasks( @RequestParam Map<String,Object> params){
 		return listMyCandidateUserTasks(params);
	} 

	/**
	 * 新增一条数据
	 */
	@RequestMapping(value="/addComment")
	public Result addComment(@RequestBody Map<String,Object> comment) {

			String userid=(String) comment.get("userid");
			String taskId=(String)comment.get("taskId");
			String procInstId=(String)comment.get("procInstId");
			String commentMsg=(String)comment.get("commentMsg");
			if(org.apache.commons.lang3.StringUtils.isEmpty(commentMsg)) {
				return Result.error("commentMsg-no-value","commentMsg","办理意见不能为空");
			}
			if(org.apache.commons.lang3.StringUtils.isEmpty(taskId)) {
				return Result.error("taskId-no-value","taskId","任务编号不能为空");
			}
			if(org.apache.commons.lang3.StringUtils.isEmpty(procInstId)) {
				return Result.error("procInstId-no-value","procInstId","实例编号不能为空");
			}

			if(org.apache.commons.lang3.StringUtils.isEmpty(userid)) {
				return Result.error("userid-no-value","userid","用户编号不能为空");
			}
			taskService.addCommentMsg(taskId, procInstId, commentMsg);
			return ok();
	}
	/**
	 * 任务节点的统一提交接口
	 */
	@RequestMapping(value="/complete",method = RequestMethod.POST)
	public Result complete(@RequestBody TaskActionVo reqVO) {
			if (reqVO.getAction().getName().equals(TaskAction.delegate.getName())) {
				taskService.delegateTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.transfer.getName())) {
				taskService.transferTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.sponsors.getName())) {
				taskService.sponsorsTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.agree.getName())) {
				taskService.agreeTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.disAgree.getName())) {
				taskService.disAgreeTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.reject.getName())) {
				taskService.rejectTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.rollback.getName())) {
				taskService.rollbackTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.addSign.getName())) {
				taskService.createSignTask(reqVO);
			} else if (reqVO.getAction().getName().equals(TaskAction.subSign.getName())) {
				taskService.deleteSignTask(reqVO);
			} else {
				return Result.error("not-sup-task-action", "暂时不支持的任务操作%s", reqVO.getAction().getName());
			}
			return ok();
	}


	@GetMapping("/listCandDelSign")
	@Operation(summary = "查询可以被减签的任务列表") // 目前用于，减签的时候，获得子任务列表
 	public Result getTaskListByParentTaskId(@RequestParam("parentTaskId") String parentTaskId) {
		List<org.flowable.task.api.Task> taskList = taskService.getTaskListByParentTaskId(parentTaskId);
		return Result.ok().setData(taskList).setTotal(taskList.size());

	}

}
